package com.byzk.p2p.admin.base.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.byzk.p2p.admin.base.util.JsonMsg;
import com.byzk.p2p.admin.system.dto.Resource;
import com.byzk.p2p.admin.system.service.ResourceService;

@Controller
@RequestMapping("/file")
@Scope("prototype")
public class FileController extends BaseController {

	@Autowired
	private ResourceService resourceService;
	
	
	private final static String FORMAT = "/yyyy/MM/dd/";
	private final static String FOLDER = "/static/upload";

	/**
	 * 生成目录
	 * @return
	 */
	public String generateFolder(){
		return FOLDER + new SimpleDateFormat(FORMAT).format(new Date());
	}
	
	
	/**
	 * 生成 UUID 文件名称
	 * @param fileName
	 * @return
	 */
	public String generateFileName(String fileName){
		String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
		return (UUID.randomUUID() + suffix).replace("-", "");
	}
	
	@RequestMapping(value = "/upload", method = RequestMethod.POST)  
    public String onSubmit(HttpServletRequest request, 
    		MultipartFile file,
            HttpServletResponse response)  
            throws Exception {  
		if (getUserId() == null) {
			super.printJSON(new JsonMsg(0, "请先登录！"));
			return null;
		}
	    // 文件前缀
        String prefix = generateFolder();
        // 生成文件的绝对路径
        String sysPath = System.getProperty("static.file.path");
        String path = "";
        if(StringUtils.isEmpty(sysPath)){
            path = request.getSession().getServletContext().getRealPath(prefix);
        }else{
            path += sysPath + "/" + prefix;
        }
        // 原始文件名称
        String fileName = generateFileName(file.getOriginalFilename());
        // 创建图片文件
        File targetFile = new File(path, fileName);  
        if(!targetFile.exists()){  
            targetFile.mkdirs();  
        }  
        //保存  
        try {  
            file.transferTo(targetFile);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }
        Integer id=resourceService.saveToResource(prefix+fileName,fileName,request.getRemoteAddr(), getUserId()+"","PC");
        super.printJSON(new JsonMsg(-1, "上传成功",id));
        return null;
    }  
  
	/**
	 * 上传资质审核图片（打水印）
	 * @param request
	 * @param file
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/uploadAuthFile", method = RequestMethod.POST) 
	public ResponseEntity<?> uploadFile(HttpServletRequest request,
                                        MultipartFile file,
                                        HttpServletResponse response)throws Exception {
		if (getUserId() == null) {
			super.printJSON(new JsonMsg(0, "请先登录！"));
			return null;
		}
	    // 文件前缀
        String prefix = generateFolder();
        // 生成文件的绝对路径
        String sysPath = System.getProperty("static.file.path");
        String path = "";
        if(StringUtils.isEmpty(sysPath)){
            path = request.getSession().getServletContext().getRealPath(prefix);
        }else{
            path += sysPath + "/" + prefix;
        }
        // 原始文件名称
        String fileName = generateFileName(file.getOriginalFilename());
        // 创建图片文件
        File targetFile = new File(path, fileName);  
        if(!targetFile.exists()){  
            targetFile.mkdirs();  
        }  
        //保存  
        try {  
            file.transferTo(targetFile);  
            //生成图片水印
            //@SuppressWarnings("deprecation")
    		//String iconPath = request.getRealPath("/static/images/mark_icon.png");//水印图片
            //ImageMarkUtil.pressImage(iconPath, path.replaceAll("\\\\", "/")+fileName, 0, 0);
        } catch (Exception e) {  
            e.printStackTrace();  
        }
        Integer id=resourceService.saveToResource(prefix+fileName,fileName,request.getRemoteAddr(), getUserId()+"","PC");
        //return null;
        return new ResponseEntity(id, HttpStatus.OK);
    }  
	
    // @ModelAttribute("files")//此属性用于初始类时调用,但上传文件后不能时时反应上传文件个数,不适合动态数据  
    public List<String> loadFiles(HttpServletRequest request) {  
        List<String> files = new ArrayList<String>();  
        String ctxPath = request.getSession().getServletContext().getRealPath(  
                "/")  
                + "\\" + "upload\\";  
        File file = new File(ctxPath);  
        if (file.exists()) {  
            File[] fs = file.listFiles();  
            String fname = null;  
            for (File f : fs) {  
                fname = f.getName();  
                if (f.isFile()) {  
                    files.add(fname);  
                }  
            }  
        }  
        return files;  
    }  
  
    @RequestMapping("/download/{fileName}")  
    public ModelAndView download(@PathVariable("fileName")  
    String fileName, HttpServletRequest request, HttpServletResponse response)  
            throws Exception {  
  
        response.setContentType("text/html;charset=utf-8");  
        request.setCharacterEncoding("UTF-8");  
        java.io.BufferedInputStream bis = null;  
        java.io.BufferedOutputStream bos = null;  
  
        String ctxPath = request.getSession().getServletContext().getRealPath(  
                "/")  
                + "\\" + "upload\\";  
        String downLoadPath = ctxPath + fileName;  
        System.out.println(downLoadPath);  
        try {  
            long fileLength = new File(downLoadPath).length();  
            response.setContentType("application/x-msdownload;");  
            response.setHeader("Content-disposition", "attachment; filename="  
                    + new String(fileName.getBytes("utf-8"), "ISO8859-1"));  
            response.setHeader("Content-Length", String.valueOf(fileLength));  
            bis = new BufferedInputStream(new FileInputStream(downLoadPath));  
            bos = new BufferedOutputStream(response.getOutputStream());  
            byte[] buff = new byte[2048];  
            int bytesRead;  
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
                bos.write(buff, 0, bytesRead);  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            if (bis != null)  
                bis.close();  
            if (bos != null)  
                bos.close();  
        }  
        return null;  
    }  
    
    
    @RequestMapping(value="/delete1",method=RequestMethod.POST) 
    public void deleteResource1(@RequestParam(value="resourceId", required=true)String resourceId) throws Exception{ 
    	Integer resId = Integer.parseInt(resourceId);
    	Resource resource = resourceService.getResourceById(resId);
    	if (resource == null) {
    		printJSON(new JsonMsg(1, "资源未找到,删除失败！"));
    		return;
		}
    	Integer i = resourceService.deleteResource(resId);
    	if (i>0) {
			printJSON(new JsonMsg(-1, "删除成功"));
		}else{
			printJSON(new JsonMsg(0, "删除失败"));
		}
    }
    
    @RequestMapping(value="/delete",method = RequestMethod.POST)
    public int deleteResource(@RequestParam(value="resourceId", required=true)String resourceId) throws Exception{ 
    	Integer resId = Integer.parseInt(resourceId);
    	Resource resource = resourceService.getResourceById(resId);
    	if (resource == null) {
    		printJSON(new JsonMsg(1, "资源未找到,删除失败！"));
    		return 0;
		}
    	Integer i = resourceService.deleteResource(resId);
    	return i;
    }

	@RequestMapping(value = "/editor/config", method = RequestMethod.GET)
	public ModelAndView editorConfig(@RequestParam("action") String action){
	    return new ModelAndView("/admin/base/EditorConfig");
	}
	
	/**
	 * UEditor 编辑器图片上传
	 * @param action
	 * @param file
	 * @param request
	 * @return
	 */
    @RequestMapping(value = "/editor/config", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject editorProcesser(@RequestParam String action, @RequestParam(required = false) MultipartFile file, HttpServletRequest request){
       JSONObject json = new JSONObject(); 
       if(StringUtils.equals("uploadimage", action)){
   	       // 文件前缀
           String prefix = generateFolder();
           // 生成文件的绝对路径
           String sysPath = System.getProperty("static.file.path");
           String path = "";
           if(StringUtils.isEmpty(sysPath)){
               path = request.getSession().getServletContext().getRealPath(prefix);
           }else{
               path += sysPath + "/" + prefix;
           }
           // 原始文件名称
           String fileName = generateFileName(file.getOriginalFilename());
           // 创建图片文件
           File targetFile = new File(path, fileName);  
           if(!targetFile.exists()){  
               targetFile.mkdirs();  
           }  
           //保存  
           try {  
               file.transferTo(targetFile);  
           } catch (Exception e) {  
               e.printStackTrace();  
           }
           Integer id=resourceService.saveToResource(prefix+fileName,fileName,request.getRemoteAddr(), getUserId()+"","PC");
           json.put("state", "SUCCESS");
           json.put("url", prefix+fileName);
        }else{
        	json.put("state", "error");
        } 
        return json;
    }

}  

